package com.example.gybicycle.service;

import java.util.ArrayList;
import java.util.Date;
import com.example.gybicycle.common.entity.Result;
import com.example.gybicycle.common.enums.NumType;
import com.example.gybicycle.common.sql.CrudService;
import com.example.gybicycle.common.util.NumberUtil;
import com.example.gybicycle.dao.LockDao;
import com.example.gybicycle.entity.Bike;
import com.example.gybicycle.entity.BikePoint;
import com.example.gybicycle.dao.BikePointDao;
import com.example.gybicycle.entity.Lock;
import com.example.gybicycle.entity.LockSel;
import com.example.gybicycle.entity.wx.BikePointCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BikePointService extends CrudService<BikePointDao, BikePoint> {
    @Autowired
    private LockDao lockDao;
    @Override
    public BikePoint get(String id) {
        BikePoint table=super.get(id);
        if(table!=null){
            Lock lock=new Lock();
            lock.setBikePointId(id);
            List<LockSel> lockSels=lockDao.findSelect(lock);
            table.setLockSels(lockSels);
            if(lockSels.size()>0){
                table.setLocks(lockSels.stream().filter( sel->sel.getIsSel().equals(true)).map(LockSel::getId).collect(Collectors.toList()));
            }else table.setLocks(new ArrayList<>());

        }
        return table;
    }
    public Result save(BikePoint entity,String loginId){
        int num=0;
        if(entity.getId()==null){           
            num=dao.insert(entity);
        }else {
           
            num=dao.update(entity);
        }
        if(num>0)
            return Result.success(entity);
        else 
            return Result.fail("保存失败");
    }

    @Override
    public int insert(BikePoint entity) {
        entity.setId(NumberUtil.getNum(NumType.POINT));
        int num=super.insert(entity);
        if(num>0&&(entity.getLocks()!=null&&entity.getLocks().size()>0)){
             dao.addLock(entity.getId(),entity.getLocks());
        }
        return  num;
    }

    @Override
    public int update(BikePoint entity) {
        int num= super.update(entity);
        if(num>0){
            dao.delOldLock(entity.getId());
            if(entity.getLocks()!=null&&entity.getLocks().size()>0)
                num=dao.addLock(entity.getId(),entity.getLocks());
        }
        return num;
    }

    @Override
    public int insertByList(List<BikePoint> list) {
        for(BikePoint entity:list){
            entity.setId(NumberUtil.getNum(NumType.POINT));
        }
        return super.insertByList(list);
    }

    public List<BikePoint> findList(BikePoint entity){
        List<BikePoint> list=super.findList(entity);
        return list;
    }
    public List<BikePointCount> findPoint(){
        return dao.findPoint();
    }

}